<template>
  <view class="document-detail-container">
    <!-- 顶部导航栏 -->
    <view class="header">
      <view class="header-content">
        <view class="back-section" @click="goBack">
          <text class="back-icon">←</text>
          <text class="header-title">文档详情</text>
        </view>
        <view class="header-actions">
          <button class="action-btn" @click="showActions">
            <text class="action-icon">⋮</text>
          </button>
        </view>
      </view>
    </view>

    <!-- 文档信息卡片 -->
    <view class="info-card">
      <view class="document-icon">
        <text class="icon-text">{{ getFileIcon(document.fileName) }}</text>
      </view>
      <view class="document-info">
        <text class="document-name">{{ document.fileName }}</text>
        <view class="info-row">
          <text class="info-label">大小：</text>
          <text class="info-value">{{ formatFileSize(document.fileSize || 0) }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">上传时间：</text>
          <text class="info-value">{{ formatDateTime(document.uploadedAt) }}</text>
        </view>
        <view class="info-row">
          <text class="info-label">状态：</text>
          <text class="status-text" :class="getStatusClass(document.status)">
            {{ getStatusText(document.status) }}
          </text>
        </view>
        <view class="info-row">
          <text class="info-label">分块数：</text>
          <text class="info-value">{{ document.chunkCount || 0 }}</text>
        </view>
      </view>
    </view>

    <!-- 分块列表 -->
    <view class="chunks-section">
      <view class="section-header">
        <text class="section-title">文档分块</text>
        <text class="section-count">({{ chunks.length }})</text>
      </view>
      
      <scroll-view
        class="chunks-list"
        scroll-y="true"
        @scrolltolower="loadMoreChunks"
        refresher-enabled="true"
        :refresher-triggered="refreshing"
        @refresherrefresh="refreshChunks"
      >
        <view v-if="chunks.length === 0 && !loading" class="empty-state">
          <text class="empty-icon">📄</text>
          <text class="empty-text">暂无分块信息</text>
        </view>

        <view v-else class="chunks-grid">
          <view
            v-for="(chunk, index) in chunks"
            :key="chunk.id"
            class="chunk-card"
            @click="viewChunk(chunk)"
          >
            <view class="chunk-header">
              <text class="chunk-index">#{{ index + 1 }}</text>
              <text class="chunk-size">{{ chunk.content.length }}字符</text>
            </view>
            <text class="chunk-content">{{ truncateText(chunk.content, 100) }}</text>
            <view class="chunk-footer">
              <text class="chunk-similarity">相似度权重: {{ chunk.similarityWeight || 1.0 }}</text>
            </view>
          </view>
        </view>

        <!-- 加载更多 -->
        <view v-if="loading" class="loading-more">
          <text class="loading-text">加载中...</text>
        </view>

        <view v-if="noMore && chunks.length > 0" class="no-more">
          <text class="no-more-text">没有更多分块了</text>
        </view>
      </scroll-view>
    </view>

    <!-- 操作菜单弹窗 -->
    <view v-if="showActionsFlag" class="actions-overlay" @click="hideActions">
      <view class="actions-dialog" @click.stop>
        <view class="actions-header">
          <text class="actions-title">文档操作</text>
        </view>
        <view class="actions-list">
          <button class="action-item" @click="reindexDocument">
            <text class="action-icon">🔄</text>
            <text>重新索引</text>
          </button>
          <button class="action-item delete-action" @click="deleteDocument">
            <text class="action-icon">🗑️</text>
            <text>删除文档</text>
          </button>
        </view>
        <button class="cancel-btn" @click="hideActions">取消</button>
      </view>
    </view>

    <!-- 分块详情弹窗 -->
    <view v-if="showChunkDetail" class="detail-overlay" @click="hideChunkDetail">
      <view class="detail-dialog" @click.stop>
        <view class="detail-header">
          <text class="detail-title">分块详情</text>
          <button class="close-btn" @click="hideChunkDetail">✕</button>
        </view>
        <view class="detail-content">
          <view class="detail-item">
            <text class="detail-label">分块编号：</text>
            <text class="detail-value">#{{ currentChunk?.chunkIndex + 1 }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">字符数：</text>
            <text class="detail-value">{{ currentChunk?.content?.length || 0 }}</text>
          </view>
          <view class="detail-item">
            <text class="detail-label">相似度权重：</text>
            <text class="detail-value">{{ currentChunk?.similarityWeight || 1.0 }}</text>
          </view>
          <view class="detail-item full-width">
            <text class="detail-label">内容：</text>
            <text class="detail-content">{{ currentChunk?.content || '' }}</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue'
import { documentAPI } from '@/api/index'
import { 
  getFileIcon, 
  formatFileSize, 
  getStatusText, 
  getStatusClass,
  formatDateTime,
  truncateText
} from '@/utils/document.js'

// 获取页面参数
const props = defineProps({
  id: {
    type: String,
    required: true
  }
})

// 响应式数据
const document = ref({})
const chunks = ref([])
const loading = ref(false)
const refreshing = ref(false)
const showActionsFlag = ref(false)
const showChunkDetail = ref(false)
const currentChunk = ref(null)
const page = ref(1)
const pageSize = ref(10)
const total = ref(0)

// 计算属性
const noMore = computed(() => chunks.value.length >= total.value && total.value > 0)

// 生命周期
onMounted(() => {
  loadDocumentDetail()
  loadChunks()
})

// 加载文档详情
const loadDocumentDetail = async () => {
  try {
    uni.showLoading({ title: '加载中...' })
    const response = await documentAPI.getDetail(props.id)
    
    console.log('文档详情API响应:', response)
    
    // 检查不同的响应格式
    const documentData = response.data || response
    
    if (documentData && documentData.id) {
      const processedDocument = {
        ...documentData,
        fileName: documentData.title || documentData.Title,
        fileSize: documentData.content ? documentData.content.length : 0,
        uploadedAt: documentData.createdAt || documentData.CreatedAt,
        status: documentData.errorMessage ? 'error' : 'success',
        chunkCount: documentData.chunksCount || documentData.ChunksCount || 0,
        formattedSize: formatFileSize(documentData.content ? documentData.content.length : 0),
        formattedDate: formatDateTime(documentData.createdAt || documentData.CreatedAt)
      }
      
      console.log('处理后的文档数据:', processedDocument)
      document.value = processedDocument
    }
  } catch (error) {
    console.error('加载文档详情失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

// 加载分块信息
const loadChunks = async (refresh = false) => {
  if (refresh) {
    page.value = 1
    chunks.value = []
  }
  
  if (loading.value) return
  
  try {
    loading.value = true
    const response = await documentAPI.getChunks(props.id, page.value, pageSize.value)
    
    console.log('分块API响应:', response)
    
    // 检查不同的响应格式
    const chunksData = response.data || response
    const items = chunksData.items || chunksData.Items || chunksData.data || []
    const totalCount = chunksData.totalCount || chunksData.TotalCount || chunksData.total || 0
    
    if (items.length > 0 || totalCount > 0) {
      const formattedItems = items.map(chunk => ({
        ...chunk,
        formattedContent: truncateText(chunk.content, 100)
      }))
      
      if (refresh) {
        chunks.value = formattedItems
      } else {
        chunks.value.push(...formattedItems)
      }
      total.value = totalCount
    }
  } catch (error) {
    console.error('加载分块失败:', error)
    uni.showToast({
      title: '加载失败',
      icon: 'none'
    })
  } finally {
    loading.value = false
    refreshing.value = false
  }
}

// 下拉刷新
const refreshChunks = () => {
  refreshing.value = true
  loadChunks(true)
}

// 加载更多
const loadMoreChunks = () => {
  if (!noMore.value && !loading.value) {
    page.value++
    loadChunks()
  }
}

// 返回上一页
const goBack = () => {
  uni.navigateBack()
}

// 文档操作
const showActions = () => {
  showActionsFlag.value = true
}

const hideActions = () => {
  showActionsFlag.value = false
}

const reindexDocument = async () => {
  try {
    uni.showLoading({ title: '重新索引中...' })
    await documentAPI.reindex(props.id)
    
    uni.showToast({
      title: '重新索引成功',
      icon: 'success'
    })
    
    hideActions()
    loadDocumentDetail()
    loadChunks(true)
  } catch (error) {
    console.error('重新索引失败:', error)
    uni.showToast({
      title: '重新索引失败',
      icon: 'none'
    })
  } finally {
    uni.hideLoading()
  }
}

const deleteDocument = async () => {
  uni.showModal({
    title: '确认删除',
    content: `确定要删除文档 "${document.value.fileName}" 吗？`,
    success: async (res) => {
      if (res.confirm) {
        try {
          uni.showLoading({ title: '删除中...' })
          await documentAPI.delete(props.id)
          
          uni.showToast({
            title: '删除成功',
            icon: 'success'
          })
          
          hideActions()
          uni.navigateBack()
        } catch (error) {
          console.error('删除失败:', error)
          uni.showToast({
            title: '删除失败',
            icon: 'none'
          })
        } finally {
          uni.hideLoading()
        }
      }
    }
  })
}

// 分块操作
const viewChunk = (chunk) => {
  currentChunk.value = {
    ...chunk,
    formattedContent: chunk.content
  }
  showChunkDetail.value = true
}

const hideChunkDetail = () => {
  showChunkDetail.value = false
  currentChunk.value = null
}
</script>

<style lang="scss" scoped>
.document-detail-container {
  height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  display: flex;
  flex-direction: column;
}

.header {
  padding: 40rpx 40rpx 20rpx;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20rpx);
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.back-section {
  display: flex;
  align-items: center;
  gap: 20rpx;
}

.back-icon {
  font-size: 40rpx;
  color: white;
}

.header-title {
  font-size: 40rpx;
  font-weight: bold;
  color: white;
}

.action-btn {
  background: rgba(255, 255, 255, 0.2);
  border: none;
  border-radius: 50%;
  width: 80rpx;
  height: 80rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.action-icon {
  font-size: 32rpx;
  color: white;
}

.info-card {
  margin: 40rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20rpx;
  padding: 40rpx;
  backdrop-filter: blur(10rpx);
  display: flex;
  gap: 30rpx;
  align-items: center;
}

.document-icon {
  flex-shrink: 0;
}

.icon-text {
  font-size: 80rpx;
}

.document-info {
  flex: 1;
}

.document-name {
  display: block;
  font-size: 36rpx;
  font-weight: bold;
  color: white;
  margin-bottom: 20rpx;
}

.info-row {
  display: flex;
  margin-bottom: 15rpx;
}

.info-label {
  color: rgba(255, 255, 255, 0.7);
  min-width: 120rpx;
}

.info-value {
  color: white;
  flex: 1;
}

.status-text {
  padding: 5rpx 15rpx;
  border-radius: 20rpx;
  font-size: 24rpx;
}

.status-pending {
  background: rgba(255, 193, 7, 0.3);
  color: #ffc107;
}

.status-processing {
  background: rgba(0, 123, 255, 0.3);
  color: #007bff;
}

.status-completed {
  background: rgba(40, 167, 69, 0.3);
  color: #28a745;
}

.status-failed {
  background: rgba(220, 53, 69, 0.3);
  color: #dc3545;
}

.chunks-section {
  flex: 1;
  margin: 0 40rpx 40rpx;
  background: rgba(255, 255, 255, 0.2);
  border-radius: 20rpx;
  backdrop-filter: blur(10rpx);
  display: flex;
  flex-direction: column;
}

.section-header {
  padding: 30rpx;
  border-bottom: 1rpx solid rgba(255, 255, 255, 0.2);
  display: flex;
  align-items: center;
  gap: 10rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: white;
}

.section-count {
  color: rgba(255, 255, 255, 0.7);
  font-size: 28rpx;
}

.chunks-list {
  flex: 1;
  padding: 20rpx;
}

.empty-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 400rpx;
  gap: 20rpx;
}

.empty-icon {
  font-size: 80rpx;
  color: rgba(255, 255, 255, 0.5);
}

.empty-text {
  font-size: 32rpx;
  color: rgba(255, 255, 255, 0.7);
}

.chunks-grid {
  display: grid;
  gap: 20rpx;
}

.chunk-card {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 15rpx;
  padding: 30rpx;
  backdrop-filter: blur(5rpx);
  transition: all 0.3s ease;
}

.chunk-card:active {
  transform: scale(0.98);
}

.chunk-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15rpx;
}

.chunk-index {
  font-size: 28rpx;
  font-weight: bold;
  color: white;
}

.chunk-size {
  font-size: 24rpx;
  color: rgba(255, 255, 255, 0.7);
}

.chunk-content {
  font-size: 26rpx;
  color: rgba(255, 255, 255, 0.9);
  line-height: 1.5;
  margin-bottom: 15rpx;
}

.chunk-footer {
  display: flex;
  justify-content: flex-end;
}

.chunk-similarity {
  font-size: 22rpx;
  color: rgba(255, 255, 255, 0.7);
}

.loading-more, .no-more {
  text-align: center;
  padding: 40rpx;
}

.loading-text, .no-more-text {
  color: rgba(255, 255, 255, 0.7);
  font-size: 28rpx;
}

/* 弹窗样式 */
.actions-overlay, .detail-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.actions-dialog, .detail-dialog {
  background: white;
  border-radius: 20rpx;
  width: 80%;
  max-width: 600rpx;
  max-height: 80vh;
  overflow-y: auto;
}

.actions-header, .detail-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.actions-title, .detail-title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 40rpx;
  color: #999;
}

.actions-list, .detail-content {
  padding: 40rpx;
}

.action-item {
  width: 100%;
  padding: 30rpx;
  border: none;
  border-bottom: 1rpx solid #eee;
  background: none;
  display: flex;
  align-items: center;
  gap: 20rpx;
  font-size: 32rpx;
  color: #333;
}

.action-item:last-child {
  border-bottom: none;
}

.delete-action {
  color: #dc3545;
}

.cancel-btn {
  width: 100%;
  padding: 30rpx;
  border: none;
  border-top: 1rpx solid #eee;
  background: none;
  font-size: 32rpx;
  color: #666;
}

.detail-item {
  display: flex;
  margin-bottom: 20rpx;
}

.detail-item.full-width {
  flex-direction: column;
}

.detail-label {
  font-weight: bold;
  color: #333;
  min-width: 120rpx;
  margin-bottom: 10rpx;
}

.detail-value {
  color: #666;
  flex: 1;
}

.detail-content {
  color: #666;
  line-height: 1.6;
  white-space: pre-wrap;
}
</style>